<template>
  <div>
    <div class="vacation-box content-box" v-if="!onsearching">
      <nav-title v-if="edit" title="销假申请" :routerLink="routerLink" />
      <nav-title v-else-if="!edit" title="销假审批" :routerLink="routerLink" />

      <div class="regulations-box" v-if="!edit">
        <div class="title">基本信息</div>
        <simple-line title="员工ID" v-bind:value="allInfo.cWfEmplid" />
        <simple-line title="姓名" v-bind:value="allInfo.cWfName" />
        <simple-line title="部门" v-bind:value="allInfo.cWfDeptdescr" />
        <simple-line title="岗位" v-bind:value="allInfo.cWfJcDescr" />
        <simple-line title="职等" v-bind:value="allInfo.cWfJobLevel" />
      </div>
      <div class="regulations-box vacation-content">
        <div class="title">流程信息</div>
        <div class="information" v-for="(item, index) in allInfo.dtls" v-bind:key="'item_' + index">
          <div class="search">
            <div class="search_title">原请假流程</div>
            <input class="search_input" type="text" readonly placeholder="请选择原流程" @click="queryVacation(index)" v-model="item.cTransactionNum" />
            <img v-if="edit" class="search_img" src="./images/search.png" alt @click="queryVacation(index)" />
          </div>
          <simple-line title="原流程名称" v-bind:value="item.cWfTitle" />
          <simple-line title="原请假类型" v-bind:value="item.cLeaveType" />
          <simple-line title="原请假天数" v-bind:value="item.cLeaveDays" />
          <simple-line title="开始时间" v-bind:value="item.startDate" />
          <simple-line title="结束时间" v-bind:value="item.endDate" />
          <div class="vacation-content-add-cut" v-if="edit">
            <span @click="addClick(index)">+</span>
            <span @click="cutClick(index)">-</span>
          </div>
        </div>
        <edit-option-line :boldtitle="true" label="销假类型" :readonly="!edit" :vals="cLeaveTypes" v-model="allInfo.cCleaveType" />

        <edit-date-line label="销假开始日期" :boldtitle="true" :readonly="!edit" v-model="allInfo.startDate" @on-change="startDateChange()" />
        <edit-date-line label="销假结束日期" :boldtitle="true" :readonly="!edit" v-model="allInfo.endDate" @on-change="endDataChange()" />

        <file-line v-if="!edit" label="附件" :fileitems="allInfo.wfFiles" :boldtitle="true" />
      </div>
      <div class="regulations-box">
        <div class="regulations-box">
          <div class="info-label">销假事由</div>
          <div class="info-label-text">
            <textarea v-if="edit" placeholder="请在这里输入..." rows="5" v-model="leaveInfo"></textarea>
            <textarea v-else readonly rows="5" v-model="leaveInfo"></textarea>
          </div>
        </div>
      </div>
      <div v-if="edit" class="regulations-box">
        <div class="regulations-box">
          <div class="info-label">附件</div>
          <div class="file-list" v-for="item in fileList">
            <div class="filname">
              <span class="iplodimg">
                <a v-if="(item.fileType == 'jpg') || (item.fileType == 'png') || (item.fileType == 'pdf') || (item.fileType=='txt') || (item.fileType=='jpeg')"
                  href="javascript:;" @click="showItemClick(item)">{{item.originalName}}</a>
                <!-- <a v-else="" href="javascript:;" @click="downloadFile(item.fileUrl)">{{item.originalName}}</a> -->
                <a v-else href="javascript:;" @click="openApp(item.fileUrl, item.androidUrl)">{{item.originalName}}</a>
                <img class="delicon" v-if="edit" @click="delImg(item.seqnbr)" src="./images/delfil.png" />
              </span>
            </div>
          </div>
          <div class="wrap-load" v-if="edit">
            <div class="upload-part">
              <img src="./images/addfils.png" />
              <input @change="uploadFile" type="file" name="file" id="file" accept="image/*" />
            </div>
          </div>
        </div>
      </div>

      <div class="regulations-box">
        <div class="title">分权引用</div>
        <fqyy-line :editting="edit" :fqyyFlag="fqyyInfo.cFqyyFlag" :noFqyySum="fqyyInfo.noFqyySum" :noFqyyRatio="fqyyInfo.noFqyyRatio"
          :fqyyMsg="fqyyInfo.cFqyyDetail" ref="fqyy"></fqyy-line>
      </div>

      <show-annex :option="showItem" v-if="showDetail" :hiddenImg="hiddenImg"></show-annex>

      <button v-if="resubmit" @click="submit">重新提交</button>
      <button v-else-if="edit" @click="submit">提交</button>
      <!-- 流程图 -->
      <div class="regulations-box" v-if="!edit">
        <div class="title">流程图</div>
        <v-flow-charts :transNum="cTransactionNbr" :loginOprid="loginOprid"></v-flow-charts>
      </div>
      <!-- 审批意见 -->
      <div class="regulations-box" v-if="approved == '0'  && allInfo.cIsChuanyue != 'Y'">
        <div class="info-label">审批意见</div>
        <div class="info-label-text">
          <textarea v-if="approved == '0'" placeholder="请在这里输入..." rows="5" v-model="cComments"></textarea>
          <textarea v-else readonly rows="5" v-model="cComments"></textarea>
        </div>
      </div>

      <div style="height: 50px" v-if="!edit"></div>
      <!-- 底部按钮 -->
      <div v-if="approved == '0'">
        <operation-btn :cApprovalSw="allInfo.cApprovalSw" :cDenySw="allInfo.cDenySw" :cPushbackAllSw="allInfo.cPushbackAllSw"
          :cAddSw="allInfo.cAddSw" :cTransactionNbr="allInfo.cTransactionNbr" :cWfType="allInfo.cWfType" :cReadSw="allInfo.cIsChuanyue"
          :cStepType="allInfo.cStepType" :cComments="cComments"></operation-btn>
      </div>
    </div>
    <div v-if="onsearching">
      <!-- header部分 -->
      <!-- <div class="container clearfix">
        <div class="search clearfix">
          <img class="search-img" src="./images/user.png" alt="" @click="searchVisa">&nbsp;
          <input class="search-input" type="text" placeholder="请输入姓名关键字" v-model="searchText">
          <img class="search-img" src="./images/searchicon.png" alt="" @click="searchVisa">
        </div>
      </div>-->

      <div style="height:30px;width:100%">&nbsp;</div>
      <label v-for="(item,index) in vacalist" class="vacation-item" :for="'vaca_'+index" v-bind:key="'vacation_' + index">
        <div>
          <input type="radio" :id="'vaca_'+index" name="vacationBox" :value="item.cTransactionNbr" />
          <i></i>
          <label :for="'vaca_'+index" class="name">{{item.cWfTitle}}</label>
        </div>
        <div>请假时间：{{item.cWfAppDt}}</div>
        <div>请假类型：{{item.cLeaveTypeValue}}</div>
        <div>请假天数：{{item.cPleaveDays}}</div>
        <div>编号：{{item.cTransactionNum}}</div>
      </label>
      <div style="height:100px;width:100%">&nbsp;</div>
      <div class="confirm-btn">
        <button @click="choseVaca">确定</button>
      </div>
      <div style="height:30px;width:100%">&nbsp;</div>
    </div>
  </div>
</template>

<script>
  import {
  vacationsaveSel,
  getDicItem,
  getLeaveType,
  getWfSelHdr,
  getCompensateApprove,
  delWfFile,
  getSavedPlave,
  saveWfCleaHdr,
  getWfCleaHdr,
  getSavedList,
  getFqyyInfo,
  saveFqyyInfo
} from "../../api/api";
import fqyyLine from "../../components/basic/FqyyLine";
import CommonUtil from "../../components/basic/util";
import { Datetime, Group, PopupRadio, dateFormat } from "vux";
import FileLine from "../../components/basic/FileLine";
import EditOptionLine from "../../components/basic/EditOptionLine";
import EditDateLine from "../../components/basic/EditDateLine";
import SimpleLine from "../../components/basic/SimpleLine";
import vFlowCharts from "../formalStaff/common/flowChart";
import operationBtn from "../formalStaff/common/operationBtn";
import qs from "qs";
import moment from "moment";
import cloneDeep from "lodash/clonedeep";
import { imgPreview, postImg } from "../../util/uploadImg";
export default {
  name: "Vacation",
  components: {
    operationBtn,
    Datetime,
    Group,
    PopupRadio,
    vFlowCharts,
    EditOptionLine,
    EditDateLine,
    SimpleLine,
    FileLine,
    fqyyLine
  },
  created() {},
  mounted() {
    CommonUtil.tryLogin(this).then(() => {
      this.cTransactionNbr = this.$route.query.cTransactionNbr;
      this.approved = this.$route.query.approved;
      this.loginOprid = this.$route.query.token;
      this.cWfType = "SEL";
      this.allInfo.dtls.push(this.initItem());
      if (this.$route.query.approved || this.$route.query.approved == 0) {
        this.getData();
        this.edit = false;
      } else {
        if (this.$route.query.cTransactionNbr) {
          this.getData();
          this.resubmit = true;
        }
      }
      getFqyyInfo({
        cTransactionNbr: this.cTransactionNbr,
        processType: "unvacation"
      }).then(res => {
        this.fqyyInfo = res.retData;
      });
      this.emplid = this.$route.query.emplid;
      CommonUtil.loadDic(
        this.cLeaveTypes,
        "C_CLEAVE_TYPE",
        "xlatshortname",
        "fieldvalue"
      );
    });
  },
  data() {
    return {
      fqyyInfo: {
        fqyyFlag: "",
        fqyyDetail: ""
      },
      cLeaveTypes: [],
      cCleaveType: "",

      onsearching: false,
      vacalist: [],

      chosedIndex: -1,
      chosedDtlIndex: -1,

      resubmit: false,
      type: false,
      cWfType: "",
      routerLink: "",
      cTransactionNbr: "",
      approved: "",
      edit: true,
      emplid: "",
      leaveInfo: "",
      cComments: "",
      showGroup: false,
      showItem: {},
      showDetail: false,
      fileList: [
        // { attachsysfilename: '123.png' }
      ],

      plaveItem: {},
      allInfo: {
        dtls: []
      }
    };
  },
  methods: {
    getRadioIndex(name) {
      let rname = document.getElementsByName(name);
      var strNew;
      for (var i = 0; i < rname.length; i++) {
        if (rname.item(i).checked) {
          return i;
        }
      }
      return -1;
    },
    initItem() {
      return {
        cTransactionNum: "",
        cWfTitle: "",
        cLeaveType: "",
        cLeaveDays: 0,
        startDate: "",
        endDate: ""
      };
    },
    choseVaca() {
      let v = this.getRadioIndex("vacationBox");

      console.error(v);
      if (v >= 0) {
        let dtl = this.allInfo.dtls[this.chosedDtlIndex];
        let vac = this.vacalist[v];
        dtl.cTransactionNum = vac.cTransactionNum;
        dtl.cWfTitle = vac.cWfTitle;
        dtl.cLeaveType = vac.cLeaveTypeValue;
        dtl.cLeaveDays = vac.cPleaveDays;
        dtl.startDate = vac.startDate;
        dtl.endDate = vac.endDate;
      }
      this.onsearching = false;
      // this.vacalist.push({})
    },
    queryVacation(idx) {
      this.$vux.loading.show();
      this.onsearching = true;
      var _this = this;

      this.chosedDtlIndex = idx;

      getSavedList({})
        .then(res => {
          _this.$vux.loading.hide();

          if (res && res.retCode === "000000") {
            _this.vacalist.splice(0, _this.vacalist.length);
            for (let i = 0; i < res.retData.length; i++) {
              _this.vacalist.push(res.retData[i]);
            }
          }
        })
        .catch(res => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "警告",
            content: "网络异常，请稍后重试"
          });
        });
    },
    startDateChange(index) {
      if(this.edit) {
        if (!this.allInfo.endDate) {
          this.calcPregnantTime();
          return;
        }
        if (
          moment(this.allInfo.endDate).unix() <
          moment(this.allInfo.startDate).unix()
        ) {
          return this.$vux.alert.show({
            title: "提示",
            content: "开始日期必须小于或等于结束日期！",
            onHide: () => {
              this.allInfo.startDate = this.allInfo.endDate;
              this.calcPregnantTime();
            }
          });
        }
      }
    },
    endDataChange(index) {
      if(this.edit) {
        if (!this.allInfo.startDate) {
          return;
        }
        if (
          moment(this.allInfo.endDate).unix() <
          moment(this.allInfo.startDate).unix()
        ) {
          return this.$vux.alert.show({
            title: "提示",
            content: "结束日期必须大于或等于开始日期！",
            onHide: () => {
              this.allInfo.endDate = this.allInfo.startDate;
            }
          });
        }
      }
    },
    getData() {
      this.$vux.loading.show();
      getWfCleaHdr({
        cTransactionNbr: this.cTransactionNbr,
        loginOprid: this.loginOprid
      })
        .then(res => {
          this.$vux.loading.hide();
          if (res && res.retCode === "000000") {
            CommonUtil.updateFileUrl(res.retData.wfFiles);
            this.allInfo = res.retData;
            this.leaveInfo = res.retData.cApplInfo;
            this.cWfType = res.retData.cWfType;
            this.fileList = res.retData.wfFiles;
            document.documentElement.scrollTop = 0;
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(res => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "警告",
            content: "网络异常，请稍后重试"
          });
        });
    },
    submit() {
      this.allInfo.cApplInfo = this.leaveInfo;
      if (
        !CommonUtil.valid(
          this,
          this.allInfo,
          "cCleaveType",
          "销假类型不能为空"
        ) ||
        !CommonUtil.valid(this, this.allInfo, "cApplInfo", "请填写销假事由！")
      ) {
        return;
      }
      if (!this.allInfo.dtls || this.allInfo.dtls.length == 0) {
        this.$vux.alert.show({
          title: "警告",
          content: "请选择对应的请假记录"
        });
        return;
      }

      if (!this.allInfo.startDate || !this.allInfo.endDate) {
        this.$vux.alert.show({
          title: "警告",
          content: "请选择对应的销假开始结束时间"
        });
        return;
      }

      if (
        !this.$refs.fqyy.fqyyFlag1 ||
        (this.$refs.fqyy.fqyyFlag1[0] == "有" && !this.$refs.fqyy.fqyyMsg1)
      ) {
        this.$vux.alert.show({
          title: "提示",
          content: "分权信息不能为空"
        });
        return;
      }

      let transNums = [];
      this.allInfo.dtls.map(dtl => {
        if (!dtl.cTransactionNum) {
          this.$vux.alert.show({
            title: "警告",
            content: "请假记录流水不能为空"
          });
          return;
        } else {
          transNums.push(dtl.cTransactionNum);
        }
      });

      let params = {
        cApplInfo: this.allInfo.cApplInfo,
        transNums: transNums,
        cCleaveType: this.allInfo.cCleaveType,
        cTransactionNbr: this.cTransactionNbr,
        startDate: this.allInfo.startDate,
        endDate: this.allInfo.endDate
      };

      this.$vux.loading.show();
      saveWfCleaHdr(params)
        .then(res => {
          this.$vux.loading.hide();
          if (res && res.retCode === "000000") {
            //保存分权信息
            saveFqyyInfo({
              cTransactionNbr: res.retData,
              cFqyyFlag: this.$refs.fqyy.fqyyFlag1[0],
              cFqyyDetail: this.$refs.fqyy.fqyyMsg1
            }).then(res => {});
            this.$vux.alert.show({
              title: "成功",
              content: "申请成功",
              onHide: () => {
                // this.fileList = [];
                // this.approved = 2;
                // this.routerLink = "MyApplication";
                // this.cTransactionNbr = res.retData;
                // this.edit = false;
                // this.resubmit = false;
                // this.getData();
                this.$router.push({ name: "MyApplication" });
              }
            });
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(res => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "警告",
            content: "网络异常，请稍后重试"
          });
        });
    },
    addClick(index) {
      this.allInfo.dtls.splice(index + 1, 0, this.initItem());
    },
    cutClick(index) {
      this.allInfo.dtls.splice(index, 1);
    },
    popGroup() {
      this.showGroup = !this.showGroup;
      window.event.cancelBubble = true;
    },
    delImg(index) {
      delWfFile(
        qs.stringify({ cTransactionNbr: this.cTransactionNbr, seqnbr: index })
      )
        .then(res => {
          if (res.retCode === "000000") {
            const newList = [];
            this.fileList.map(item => {
              if (item.seqnbr != index) newList.push(item);
            });
            this.fileList = newList;
            this.$vux.alert.show({
              title: "提示",
              content: "删除成功"
            });
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(e => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "提示",
            content: "上传失败"
          });
        });
    },
    showItemClick(item) {
      this.showItem = item;
      this.showDetail = true;
    },
    hiddenImg() {
      this.showDetail = false;
    },
    uploadFile(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.picValue = files[0];
      // let haveImg = false;
      // this.fileList.map((item)=>{
      //   if (item.originalName == this.picValue.name) return haveImg = true;
      // });
      // if (haveImg) {
      //   return this.$vux.alert.show({
      //           title: "提示",
      //           content: "请不要重复上传！"
      //         });
      // }
      this.$vux.loading.show({
        text: "上传中"
      });
      imgPreview(this.picValue).then(imgRes => {
        postImg(imgRes, this.cTransactionNbr, this.cWfType, this.picValue.name)
          .then(res => {
            this.$vux.loading.hide();
            if (res.retCode === "000000") {
              this.cTransactionNbr = res.retData.cTransactionNbr;
              const obj = {
                originalName: this.picValue.name,
                fileUrl: imgRes,
                seqnbr: res.retData.seqnbr,
                fileType: this.picValue.name.split(".")[1]
              };
              this.fileList.push(obj);
              const file = document.getElementById("file");
              file.value = "";
              this.$vux.alert.show({
                title: "提示",
                content: "上传成功"
              });
            } else {
              this.$vux.alert.show({
                title: "提示",
                content: res.retMsg
              });
            }
          })
          .catch(e => {
            this.$vux.loading.hide();
            this.$vux.alert.show({
              title: "提示",
              content: "上传失败"
            });
          });
      });
    }
  }
};
</script>

<style type="text/scss" lang="scss">
  @import "./vacation.scss";
@import "../../styles/rejectmain.scss";
.search {
  width: 100%;
  height: 44px;
  border-bottom: 1px solid #e5e5e5;
  line-height: 44px;
  .search_title {
    width: 36%;
    text-align: right;
    float: left;
    padding-right: 10px;
    font-weight: 600;
  }
  .search_input {
    width: 40%;
    float: left;
    height: 44px;
  }
  .search_img {
    float: right;
    margin: 5px 20px auto auto;
    width: 30px;
    height: 30px;
  }
}

.vacation-item {
  display: block;
  padding: 10px 10px 10px 10px;
  margin: 0px 10px 10px 10px;
  text-align: left;
  background-color: #f2f2f2;
  border-radius: 4px;
  img {
    vertical-align: text-top;
  }
  .name {
    font-weight: bold;
  }
  input[type="radio"] {
    display: none;
    &:checked {
      & + i {
        border: 5px solid #1caafe;
      }
    }
  }
  i {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 1px solid #aaa;
    border-radius: 20px;
    margin-right: 10px;
    float: left;
  }
}
.confirm-btn {
  width: 100%;
  margin: 0 auto;
  color: #fff;
  position: fixed;
  bottom: 15px;
  text-align: center;
  button {
    color: white;
    font-size: 16px;
    font-weight: 900;
    line-height: 40px;
    width: 250px;
    height: 40px;
    background-color: #1caafe;
    border-radius: 4px;
  }
}
</style>
